/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jdRegistrarEmpresa.java
 *
 * Created on 01-sep-2010, 15:40:00
 */

package gestionseguridadadministrativacliente;

import administracion.delegate.GestionPedidosDelegate;
import administracion.helper.Listas;
import administracion.helper.Utiles_MensajesDialogo;
import Proveedores.jifIngresarProveedor;
import Comprobantes.jifRegistrarComprobanteDeOrden;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.MaskFormatter;
import suministros.ejb30.TO.EmpresaTO;
import suministros.ejb30.entity.Empresa;

/**
 *
 * @author Luis_Angel
 */
public class jdRegistrarEmpresa extends javax.swing.JDialog {

    private JFileChooser file;
    private Image ic;
    private ImagenEmpresa lblImagen;
    private MaskFormatter mascaraRuc;
    private byte[] logo;
    private EmpresaTO empresa_edit;
    private boolean isEdicion;
    private String restriccion;
    /** Creates new form jdRegistrarEmpresa */
    public jdRegistrarEmpresa(java.awt.Frame parent, boolean modal,boolean isEdicion) {
        super(parent, modal);
        ic =null;
         lblImagen = new ImagenEmpresa();
         this.isEdicion = isEdicion;
         if(this.isEdicion){
              this.setTitle("Modificar Empresa");
               this.restriccion="modificar";
         }
            
         else{
             this.setTitle("Nueva Empresa");
             this.restriccion="guardar";
         }
             

       //  lblImagen.setBounds(new Rectangle(10, 20, 130, 130));
        lblImagen.setText("1");
        lblImagen.setBorder(BorderFactory.createTitledBorder(""));
        lblImagen.setHorizontalAlignment(SwingConstants.CENTER);
         construirMascaras();
       initComponents();
    }

     public void setEmpresaEdit(EmpresaTO empresa) throws Exception{
        this.empresa_edit = empresa;
        this.jtfRuc.setText(empresa.getRuc());
        this.jtfRazon.setText(empresa.getRazon());
        this.jtfDireccion.setText(empresa.getDescripcion());
        this.jchbPrincipal.setSelected(empresa.getPrincipal());
        //traer logo
        logo = GestionPedidosDelegate.getInstance().getLogoEmpresa(empresa.getCodigo());
        ic = new ImageIcon(logo).getImage();
        lblImagen.repaint();
        //llenarDatosOrdenAEditar();
     }

    private void construirMascaras() {
        try {
          this.mascaraRuc = new MaskFormatter("###########");

        } catch (ParseException ex) {
          Logger.getLogger(jdRegistrarEmpresa.class.getName()).log(Level.SEVERE, null, ex);
          ex.printStackTrace();
        }
     }


    private void limpiar(){
        this.jtfDireccion.setText("");
        this.jtfRazon.setText("");
        this.jtfRuc.setText("");
        this.ic = null;
        this.lblImagen.repaint();
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel20 = new javax.swing.JLabel();
        jLabel21 = new javax.swing.JLabel();
        jLabel22 = new javax.swing.JLabel();
        jtfRazon = new javax.swing.JTextField();
        jtfDireccion = new javax.swing.JTextField();
        jtfRuc = new javax.swing.JFormattedTextField(this.mascaraRuc);
        jchbPrincipal = new javax.swing.JCheckBox();
        jpImagen = new javax.swing.JPanel();
        jbAceptar = new javax.swing.JButton();
        jbCancelar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setName("jPanel1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gestionseguridadadministrativacliente.GestionSeguridadAdministrativaclienteApp.class).getContext().getResourceMap(jdRegistrarEmpresa.class);
        jLabel20.setFont(resourceMap.getFont("jLabel20.font")); // NOI18N
        jLabel20.setText(resourceMap.getString("jLabel20.text")); // NOI18N
        jLabel20.setName("jLabel20"); // NOI18N

        jLabel21.setFont(resourceMap.getFont("jLabel21.font")); // NOI18N
        jLabel21.setText(resourceMap.getString("jLabel21.text")); // NOI18N
        jLabel21.setName("jLabel21"); // NOI18N

        jLabel22.setFont(resourceMap.getFont("jLabel22.font")); // NOI18N
        jLabel22.setText(resourceMap.getString("jLabel22.text")); // NOI18N
        jLabel22.setName("jLabel22"); // NOI18N

        jtfRazon.setText(resourceMap.getString("jtfRazon.text")); // NOI18N
        jtfRazon.setName("jtfRazon"); // NOI18N
        jtfRazon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfRazonActionPerformed(evt);
            }
        });

        jtfDireccion.setName("jtfDireccion"); // NOI18N
        jtfDireccion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfDireccionActionPerformed(evt);
            }
        });

        jtfRuc.setFont(resourceMap.getFont("jtfRuc.font")); // NOI18N
        jtfRuc.setName("jtfRuc"); // NOI18N
        jtfRuc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfRucActionPerformed(evt);
            }
        });

        jchbPrincipal.setText(resourceMap.getString("jchbPrincipal.text")); // NOI18N
        jchbPrincipal.setName("jchbPrincipal"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel21)
                    .addComponent(jLabel20)
                    .addComponent(jLabel22))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtfDireccion, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jtfRuc, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 51, Short.MAX_VALUE)
                        .addComponent(jchbPrincipal))
                    .addComponent(jtfRazon, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel20)
                    .addComponent(jtfRuc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jchbPrincipal))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel21)
                    .addComponent(jtfRazon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtfDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel22))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, -1, -1));

        jpImagen.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jpImagen.setName("jpImagen"); // NOI18N
        jpImagen.setLayout(new java.awt.BorderLayout());
        jpImagen.add(this.lblImagen);
        getContentPane().add(jpImagen, new org.netbeans.lib.awtextra.AbsoluteConstraints(432, 11, 130, 119));

        jbAceptar.setFont(resourceMap.getFont("jbAceptar.font")); // NOI18N
        jbAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_ok.png"))); // NOI18N
        jbAceptar.setMnemonic('A');
        jbAceptar.setText(resourceMap.getString("jbAceptar.text")); // NOI18N
        jbAceptar.setName("jbAceptar"); // NOI18N
        jbAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAceptarActionPerformed(evt);
            }
        });
        jbAceptar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbAceptarKeyPressed(evt);
            }
        });
        getContentPane().add(jbAceptar, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 140, -1, 20));

        jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_cancel.png"))); // NOI18N
        jbCancelar.setMnemonic('C');
        jbCancelar.setText(resourceMap.getString("jbCancelar.text")); // NOI18N
        jbCancelar.setName("jbCancelar"); // NOI18N
        jbCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCancelarActionPerformed(evt);
            }
        });
        getContentPane().add(jbCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 140, -1, 20));

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 140, -1, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAceptarActionPerformed
        try {

            int res = javax.swing.JOptionPane.showConfirmDialog( this,"Esta seguro de "+this.restriccion +"Empresa?",
      "Confirmar",javax.swing.JOptionPane.YES_NO_OPTION );
            if(res==javax.swing.JOptionPane.YES_OPTION){
                     Empresa emp = new Empresa();
                     emp.setRuc(this.jtfRuc.getText().trim());
                     emp.setRazonSocial(this.jtfRazon.getText().trim());
                     emp.setDescDireccion(this.jtfDireccion.getText().trim());
                     emp.setLogo(logo);
                     emp.setIdEmpresa((empresa_edit!=null)?empresa_edit.getCodigo():"");
                     emp.setIsPrincipal(jchbPrincipal.isSelected());
                     boolean accion_exito =false;
                     accion_exito =(!this.isEdicion)?GestionPedidosDelegate.getInstance().insertarEmpresa(emp):GestionPedidosDelegate.getInstance().actualizarEmpresa(emp);
                     if (accion_exito) {
                        Utiles_MensajesDialogo.mensajeExito();
                        limpiar();
                        Listas.refrescarEmpresas();
                    }
                    else
                        Utiles_MensajesDialogo.mensajeError("Error.. No se pudo realizar la operacion");
             }
           

        } catch (Exception ex) {
            Logger.getLogger(jdRegistrarEmpresa.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_jbAceptarActionPerformed

    private void jbAceptarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbAceptarKeyPressed

}//GEN-LAST:event_jbAceptarKeyPressed

    private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed
        
        this.dispose();
}//GEN-LAST:event_jbCancelarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
       if(file==null) {
            file=new JFileChooser();

        }

         file.setAcceptAllFileFilterUsed(false);
         FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF & PNG", "jpg", "gif", "png");
         file.setFileFilter(filter);

         int option=file.showOpenDialog(null);
         if(option == JFileChooser.APPROVE_OPTION) {
			// obtiene nombre de archivo seleccionado
                File fobject = file.getSelectedFile();
            try {
                FileInputStream streamArchivo = new FileInputStream(fobject);
                logo = new byte[(int) fobject.length()];
                streamArchivo.read(logo);
                //ic = createImage()

                String pathImage= file.getSelectedFile().getPath();
                 ic=new ImageIcon(pathImage).getImage();
                lblImagen.repaint();

           } catch (FileNotFoundException ex1) {
                Logger.getLogger(jdRegistrarEmpresa.class.getName()).log(Level.SEVERE, null, ex1);

            } catch (IOException ex) {
                Logger.getLogger(jdRegistrarEmpresa.class.getName()).log(Level.SEVERE, null, ex);

            }
         }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jtfRucActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfRucActionPerformed
        
            this.jtfRazon.requestFocus();
       
}//GEN-LAST:event_jtfRucActionPerformed

    private void jtfRazonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfRazonActionPerformed
       this.jtfDireccion.requestFocus();
    }//GEN-LAST:event_jtfRazonActionPerformed

    private void jtfDireccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfDireccionActionPerformed
       this.jbAceptar.requestFocus();
    }//GEN-LAST:event_jtfDireccionActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                jdRegistrarEmpresa dialog = new jdRegistrarEmpresa(new javax.swing.JFrame(), true,false);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

     class ImagenEmpresa extends JLabel{

        public ImagenEmpresa(){
            //updateUI();
        }

        public void paint(Graphics e){
            e.drawImage(ic,0,0,120,120,this);
        }

        public void update(Graphics e){
            paint(e);
        }

    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jbAceptar;
    private javax.swing.JButton jbCancelar;
    private javax.swing.JCheckBox jchbPrincipal;
    private javax.swing.JPanel jpImagen;
    private javax.swing.JTextField jtfDireccion;
    private javax.swing.JTextField jtfRazon;
    private javax.swing.JFormattedTextField jtfRuc;
    // End of variables declaration//GEN-END:variables

}
